#include "../../head/utils/MutiConfFile.h"
#include <QtDebug>
#include<QtSerialPort/QSerialPort>      //串口功能头文件
#include<QByteArray>
#include<QTimer>
#include<QString>
#include<QMessageBox>
#include<QCoreApplication>
#include <QTime>
#include <QDir>
#include <QTextCodec>



MutiConfFile::MutiConfFile(QObject *parent):QObject(parent)
{

}

void MutiConfFile::createFile(){
    QString sourceFile = "InitParam_low.ini";
    QString saveFile = "conf_low.ini";

    QString encryptText;
    QFile inputFile(baseUrl+sourceFile);
    if (inputFile.open(QIODevice::ReadOnly| QIODevice::Text)){
        QTextStream in(&inputFile);
        QString dataText = in.readAll();
        inputFile.close();
        qDebug()<<"-----data:\n"<<dataText;

        encryptText = encode(dataText);
        qDebug()<<"-----encryptText:\n"<<encryptText;
    }

    QFile outputFile(baseUrl+saveFile);
    if (outputFile.open(QIODevice::WriteOnly)) {
        QTextStream out(&outputFile);
        out << encryptText;
        outputFile.close();
        qDebug() << "encrypt completed.";
    } else {
        qDebug() << "Failed to open output file.";
    }


}


void MutiConfFile::readFile(QString sFile,QString desFile){
    QString sourceFile = sFile;
    QString saveFile = desFile;

    QString encryptText;
    QFile inputFile(sourceFile);
    if (inputFile.open(QIODevice::ReadOnly| QIODevice::Text)){
        QTextStream in(&inputFile);
        QString dataText = in.readAll();
        inputFile.close();
        qDebug()<<"-----data:\n"<<dataText;

        encryptText = decode(dataText);
        qDebug()<<"-----encryptText:\n"<<encryptText;
    }

    QFile outputFile(saveFile);
    if (outputFile.open(QIODevice::WriteOnly)) {
        QTextStream out(&outputFile);
        out << encryptText;
        outputFile.close();
        qDebug() << "encrypt completed.";
    } else {
        qDebug() << "Failed to open output file.";
    }
}


void MutiConfFile::deleteFile(QString fileName){
    QString sourceFile = fileName;

    QDir dir(sourceFile);
    dir.remove(fileName);
}

QString MutiConfFile::encode(const QString &plainText) {
    QTextCodec *codec = QTextCodec::codecForName("GBK");//UTF-8或者"GBK",不分大小写
    QByteArray byteArray = codec->fromUnicode(plainText).data();
    //QByteArray byteArray = plainText.toUtf8();
    QByteArray encryptedData = byteArray.toBase64();
    return QString(encryptedData);
}

QString MutiConfFile::decode(const QString &plainText) {
    QByteArray encryptedData = plainText.toLatin1();

    QByteArray decryptedData = QByteArray::fromBase64(encryptedData);
    return QString(decryptedData);

}

